package com.weijianhuawen.wjblog.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weijianhuawen.wjblog.admin.mode.vo.category.AddCategoryReqVo;
import com.weijianhuawen.wjblog.admin.mode.vo.category.DeleteCategoryReqVo;
import com.weijianhuawen.wjblog.admin.mode.vo.category.FindCategoryPageListReqVo;
import com.weijianhuawen.wjblog.admin.mode.vo.category.FindCategoryPageListRspVo;
import com.weijianhuawen.wjblog.admin.service.AdminCategoryService;
import com.weijianhuawen.wjblog.common.domain.dos.ArticleCategoryRelDo;
import com.weijianhuawen.wjblog.common.domain.dos.CategoryDo;
import com.weijianhuawen.wjblog.common.domain.mapper.ArticleCategoryRelMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.CategoryMapper;
import com.weijianhuawen.wjblog.common.enums.ResponseCodeEnum;
import com.weijianhuawen.wjblog.common.exception.BizException;
import com.weijianhuawen.wjblog.common.model.vo.SelectRspVo;
import com.weijianhuawen.wjblog.common.utils.PageResponse;
import com.weijianhuawen.wjblog.common.utils.Response;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2024-10-19 23:24
 */
@Service
@Slf4j
public class AdminCategoryServiceImpl implements AdminCategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ArticleCategoryRelMapper articleCategoryRelMapper;

    /**
     * 添加标签
     * @param vo 标签请求参数
     * @return 响应结果
     */
    @Override
    public Response addCategory(AddCategoryReqVo vo) {
        //获取分类名
        String categoryName = vo.getName();

        //判断分类名是否存在
        CategoryDo categoryDo = categoryMapper.selectByName(categoryName);
        if (Objects.nonNull(categoryDo)) {
            //已存在
            log.warn("分类名称： {}, 此分类已存在", categoryDo.getName());
            throw new BizException(ResponseCodeEnum.CATEGORY_NAME_IS_EXISTED);
        }
        categoryDo = CategoryDo.builder().name(categoryName.trim()).createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).build();
        categoryMapper.insert(categoryDo);
        return Response.success();
    }

    @Override
    public PageResponse findCategoryList(FindCategoryPageListReqVo findCategoryPageListReqVo) {
        //获取当前页，以及每一页需要展示的数量
        Long pageIndex = findCategoryPageListReqVo.getCurrent();
        Long size = findCategoryPageListReqVo.getSize();
        String categoryName = findCategoryPageListReqVo.getCategoryName();
        LocalDate startDate = findCategoryPageListReqVo.getStartDate();
        LocalDate endDate = findCategoryPageListReqVo.getEndDate();

//        //分页对象
//        Page<CategoryDo> page = new Page<>(pageIndex, size);
//
//        //构建查询条件1
//        LambdaQueryWrapper<CategoryDo> wrapper = new LambdaQueryWrapper<>();
//        String categoryName = findCategoryPageListReqVo.getCategoryName();
//        if (categoryName == null) categoryName = "";
//        LocalDate startDate = findCategoryPageListReqVo.getStartDate();
//        LocalDate endDate = findCategoryPageListReqVo.getEndDate();
//        //设置条件
//        wrapper
//                .like(StringUtils.isNotBlank(categoryName), CategoryDo::getName, categoryName.trim())
//                .ge(Objects.nonNull(startDate), CategoryDo::getCreateTime, startDate)
//                .le(Objects.nonNull(endDate), CategoryDo::getCreateTime, endDate)
//                .orderByDesc(CategoryDo::getCreateTime);

        //分页查询
        Page<CategoryDo> categoryDoPage = categoryMapper.selectPageList(pageIndex, size, categoryName, startDate, endDate);
        List<CategoryDo> categoryDos = categoryDoPage.getRecords();

        //将do转为vo
        List<FindCategoryPageListRspVo> vos = null;
        if (!Collections.isEmpty(categoryDos)) {
            vos = categoryDos.stream()
                    .map(categoryDo -> FindCategoryPageListRspVo.builder()
                            .id(categoryDo.getId())
                            .categoryName(categoryDo.getName())
                            .createTime(categoryDo.getCreateTime())
                            .articlesTotal(categoryDo.getArticlesTotal())
                            .build())
                    .collect(Collectors.toList());
        }
        if (vos == null) vos = new ArrayList<>();
        return PageResponse.success(categoryDoPage, vos);
    }

    @Override
    public Response deleteCategory(DeleteCategoryReqVo vo) {
        //获取分类id
        Long id = vo.getId();
        // 查询分类与文章关联表，如果存在分类关联的文章则不可删除
        ArticleCategoryRelDo articleCategoryRelDo = articleCategoryRelMapper.selectOneByCategoryId(id);

        if (Objects.nonNull(articleCategoryRelDo)) {
            // 该分类存在关联，无法删除
            log.warn("【分类关联服务】对应分类id:{}已被文章id:{}关联，无法删除！", articleCategoryRelDo.getCategoryId(), articleCategoryRelDo.getArticleId());
            throw new BizException(ResponseCodeEnum.CATEGORY_BIND_ARTICLE);
        }
        //删除分类
        int a = categoryMapper.deleteById(id);
        return a == 1 ? Response.success() : Response.fail(ResponseCodeEnum.NOT_EXIST_CATEGORY);
    }

    @Override
    public Response findCategorySelectList() {
        //查询所有分类
        List<CategoryDo> categoryDos = categoryMapper.selectList(null);

        //将do转换为vo
        List<SelectRspVo> selectRspVos = null;

        //获取查询的数据，如果不为空则进行转换
        if (!CollectionUtils.isEmpty(categoryDos)) {
            //将分类id作为value值，将分类名称作为label展示
            selectRspVos = categoryDos.stream()
                    .map(categoryDo -> SelectRspVo.builder()
                            .label(categoryDo.getName())
                            .value(categoryDo.getId())
                            .build())
                    .collect(Collectors.toList());
        }

        return Response.success(selectRspVos);
    }
}
